// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.

#nullable enable

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

using Elastic.Clients.Elasticsearch.Serialization;

namespace Elastic.Clients.Elasticsearch.Aggregations.Json;

public sealed class TermsExcludeConverter : JsonConverter<TermsExclude>
{
	public override TermsExclude Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
	{
		return reader.TokenType switch
		{
			JsonTokenType.StartArray => new TermsExclude(reader.ReadCollectionValue<string>(options, null)!),
			JsonTokenType.String => new TermsExclude(reader.ReadValue<string>(options)!),
			_ => throw new JsonException(
				$"Unexpected token {reader.TokenType} when deserializing {nameof(TermsExclude)}")
		};
	}

	public override void Write(Utf8JsonWriter writer, TermsExclude value, JsonSerializerOptions options)
	{
		if (value is null)
		{
			throw new ArgumentNullException(nameof(value));
		}

		if (value.Values is not null)
		{
			writer.WriteCollectionValue(options, value.Values, null);
			return;
		}

		writer.WriteStringValue(value.RegexPattern);
	}
}
